<template>
  <!-- swiper容器 -->
  <div class="swiper" ref="swiperRef">
    <!-- 轮播图区域 -->
    <div class="swiper-wrapper">
      <!-- 一张轮播图 -->
      <div class="swiper-slide" v-for="image in imageList" :key="image.id">
        <img :src="image.imgUrl" alt="banner" />
      </div>
    </div>
    <!-- 小圆点区域 -->
    <div class="swiper-pagination"></div>

    <!-- 左右翻页区域 -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
  </div>
</template>

<script>
// 引入js
import Swiper, { Navigation, Pagination, Autoplay } from "swiper";
// import Swiper from "swiper";
// import { Navigation, Pagination } from "swiper";
// 引入css
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";

export default {
  name: "XCarousel",
  // props: ["imageList"],
  props: {
    imageList: Array,
  },
  // props: {
  //   imageList: {
  //     type: Array,
  //     required: true,
  //   },
  // },
  // mounted() {
  // 等DOM元素渲染完成，才能new Swiper
  // 等imageList有值
  // },
  watch: {
    imageList: {
      handler(imageList) {
        // 首页最上面轮播图new两次，导致有bug
        // 每个轮播图只能new一次
        if (!imageList.length) return;
        // console.log(111);
        // 函数触发了，说明imageList有值了
        // 还是不能无缝轮播，原因：更新数据是同步，更新用户界面是异步
        // 等页面更新完成，在触发new Swiper
        this.$nextTick(() => {
          // 等DOM元素更新完成再触发
          new Swiper(this.$refs.swiperRef, {
            // 加载的组件
            modules: [Navigation, Pagination, Autoplay],
            // 无缝轮播
            loop: true,
            // 小圆点
            pagination: {
              el: ".swiper-pagination",
            },
            // 左右翻页
            navigation: {
              nextEl: ".swiper-button-next",
              prevEl: ".swiper-button-prev",
            },
            // 自动轮播
            autoplay: {
              delay: 1000, // 轮播间隔时间
              pauseOnMouseEnter: true, // 鼠标移入暂停轮播
              disableOnInteraction: false, // 移出继续轮播
            },
          });
        });
      },
      immediate: true, // 让监视属性第一次就触发
    },
  },
};
</script>

<style></style>
